package com.jixiang.dictionary.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jixiang.apiFeignt.clients.UserClient;
import com.jixiang.dictionary.dao.DsFileDao;
import com.jixiang.file.service.FileStorageService;
import com.jixiang.model.common.dtos.ResponseResult;
import com.jixiang.model.common.enums.AppHttpCodeEnum;
import com.jixiang.model.dictionary.entity.DsFile;
import com.jixiang.dictionary.service.DsFileService;
import com.jixiang.model.user.dtos.WxIconDtos;
import com.jixiang.utils.thread.UserThread;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.jixiang.common.constants.FileConstants.FILE_STATE_DISABLED;
import static com.jixiang.common.constants.FileConstants.FILE_STATE_TYPE;

/**
 * 图片(DsFile)表服务实现类
 *
 * @author makejava
 * @since 2023-10-17 00:13:41
 */
@Service("dsFileService")
public class DsFileServiceImpl extends ServiceImpl<DsFileDao, DsFile> implements DsFileService {

    @Autowired
    FileStorageService fileStorageService;
    @Autowired
    UserClient userClient;
    @Override
    public Boolean saveFileLog(Long userId, String url, String type, String description) {
        Boolean b = saveLog(userId, url, type, description);
        return b;
    }

    @Override
    public ResponseResult UploadImg(MultipartFile file) {
        if (file == null || file.isEmpty() || file.getSize() == 0) {

        }
        String originalFilename = file.getOriginalFilename();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYYMMddHHmmss");
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        String randomString = RandomUtil.randomString(8);
        String prestr = format + "-" + randomString;
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String imgUrl;
        try {
            imgUrl = fileStorageService.uploadImgFile("", prestr + substring, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Long userId = UserThread.getUser().getId();
        saveLog(userId,imgUrl,FILE_STATE_TYPE,"管理端用户上传文件");
        return ResponseResult.okResult(imgUrl);
    }

    @Override
    public ResponseResult UploadImgDel(String url) {
        DsFile entity = query().eq("url", url).list().get(0);
        if(!entity.getType().equals(FILE_STATE_TYPE)){
            return ResponseResult.errorResult(AppHttpCodeEnum.TYPE_ERROR,"非图片");
        }
        entity.setState(FILE_STATE_DISABLED);
        boolean update = updateById(entity);
        return ResponseResult.okResult("删除成功");
    }

    @Override
    public ResponseResult WxUploadIconImg(MultipartFile file,String oldImage) {
        if (file == null || file.isEmpty() || file.getSize() == 0) {

        }
        String originalFilename = file.getOriginalFilename();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYYMMddHHmmss");
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        String randomString = RandomUtil.randomString(8);
        String prestr = format + "-" + randomString;
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String imgUrl;
        try {
            imgUrl = fileStorageService.uploadImgFile("", prestr + substring, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Long userId = UserThread.getUser().getId();
        saveLog(userId,imgUrl,FILE_STATE_TYPE,"微信端用户上传头像文件");

        if(StrUtil.isNotBlank(oldImage)){
            List<DsFile> urlList = query().eq("url", oldImage).list();
            if(!urlList.isEmpty()){
                DsFile dsFile = urlList.get(0);
                dsFile.setState(0);
                updateById(dsFile);
            }
        }
        WxIconDtos wxIconDtos = new WxIconDtos();
        wxIconDtos.setUserId(UserThread.getUser().getId());
        wxIconDtos.setUserNewIconUrl(imgUrl);
        userClient.updateWxUserIconImage(wxIconDtos);
        return ResponseResult.okResult(imgUrl);
    }

    @Override
    public String WxUploadIconImgRes(MultipartFile file, String oldImage) {
        if (file == null || file.isEmpty() || file.getSize() == 0) {

        }
        String originalFilename = file.getOriginalFilename();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYYMMddHHmmss");
        LocalDateTime now = LocalDateTime.now();
        String format = now.format(dateTimeFormatter);
        String randomString = RandomUtil.randomString(8);
        String prestr = format + "-" + randomString;
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String imgUrl;
        try {
            imgUrl = fileStorageService.uploadImgFile("", prestr + substring, file.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        Long userId = UserThread.getUser().getId();
        saveLog(userId,imgUrl,FILE_STATE_TYPE,"微信端用户上传头像文件");

        if(StrUtil.isNotBlank(oldImage)){
            List<DsFile> urlList = query().eq("url", oldImage).list();
            if(!urlList.isEmpty()){
                DsFile dsFile = urlList.get(0);
                dsFile.setState(0);
                updateById(dsFile);
            }
        }
        WxIconDtos wxIconDtos = new WxIconDtos();
        wxIconDtos.setUserId(UserThread.getUser().getId());
        wxIconDtos.setUserNewIconUrl(imgUrl);
        userClient.updateWxUserIconImage(wxIconDtos);
        return imgUrl;
    }

    private Boolean saveLog(Long userId,String imgUrl,String type,String description) {
        DsFile dsFile = new DsFile();
        dsFile.setUrl(imgUrl);
        dsFile.setCreateUserId(userId);
        dsFile.setType(type);
        dsFile.setDescription(description);
        boolean save = save(dsFile);
        return save;
    }

}

